import base64

from django.contrib.auth.hashers import make_password
from django.db import IntegrityError
from django.http import JsonResponse, HttpResponse
from django.utils.datastructures import MultiValueDictKeyError
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

from business.business_permissions import CustomerPermission
from db_backfront_23.settings import MEDIA_ROOT, AVATAR_DIR
from user import models
from user.models import User
from user.serializers import RiderProfileSerializer, CustomerProfileSerializer, ShopProfileSerializer


# Create your views here.
@api_view(['POST'])
@permission_classes([AllowAny])  # 任何人都可以注册
def user_register(request):  # 用于用户注册的视图函数
    data = request.data
    try:
        User.objects.create(
            username=data['username'],
            password=make_password(data['password']),  # must be hushed
            user_type=data['user_type'],
            question=data['question'],
            answer=data['answer'],
            phone_num=data['phone_num']
        )
    except KeyError:
        return JsonResponse({"success": False})
    except IntegrityError:
        return JsonResponse({"success": False})
    return JsonResponse({"success": True})


@api_view(['POST'])
def update_profile(request):
    user = User.objects.get(username=request.user.username)
    try:
        new_phone_num = request.data['phone_num']
        user.phone_num = new_phone_num
        user.save()
    except KeyError:
        pass
    if user.user_type == models.CUSTOMER:
        try:
            profile = user.customer_profile
        except Exception:  # 不存在profile则创建
            serializer = CustomerProfileSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save(user=request.user)
                return JsonResponse({"success": True})
            return JsonResponse({"success": False})
        serializer = CustomerProfileSerializer(profile, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({"success": True})
        return JsonResponse({"success": False})
    elif user.user_type == models.SHOP:
        try:
            profile = user.shop_profile
        except Exception:  # 不存在profile则创建
            serializer = ShopProfileSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save(user=request.user)
                return JsonResponse({"success": True})
            return JsonResponse({"success": False})
        serializer = ShopProfileSerializer(profile, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({"success": True})
        return JsonResponse({"success": False})
    else:  # 骑手
        try:
            profile = user.rider_profile
        except Exception:
            serializer = RiderProfileSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save(user=request.user)
                return JsonResponse({"success": True})
            return JsonResponse({"success": False})
        serializer = RiderProfileSerializer(profile, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse({"success": True})
        return JsonResponse({"success": False})


@api_view(['GET'])
@permission_classes([AllowAny])
def get_question(request):
    # 获取安全问题的API
    user_name = request.GET.get('username')
    user = User.objects.get(username=user_name)
    question = user.question
    return JsonResponse({"question": question})


@api_view(['PUT'])
@permission_classes([AllowAny])
def modify_password(request):
    user_name = request.data['username']
    answer = request.data['answer']
    password = request.data['password']
    user = User.objects.get(username=user_name)
    if answer == user.answer:
        user.password = make_password(password)
        user.save()
        return JsonResponse({'success': True})
    return JsonResponse({'success': False})


@api_view(['PUT'])
def upload_avatar(request):
    try:
        new_avatar = request.FILES['avatar']
    except MultiValueDictKeyError:  # 未上传文件
        return Response({'success': False})
    user = User.objects.get(id=request.user.id)
    if user.avatar:  # 判断原本是否有头像
        user.avatar.delete()  # 删除旧头像
    user.avatar = new_avatar
    user.save()  # 保存新头像
    return JsonResponse({'success': True})


@api_view(['GET'])
def get_avatar(request):
    username = request.GET.get('username')
    user = User.objects.get(username=username)
    uid = user.id
    filename = str(uid) + '_avatar' + '.jpg'
    path = MEDIA_ROOT + '/' + AVATAR_DIR + '/' + filename
    try:
        with open(path, 'rb') as img_file:
            image_data = img_file.read()
            base64_encoded_image = base64.b64encode(image_data).decode('utf-8')
            return Response({"image": base64_encoded_image})
    except FileNotFoundError:
        return Response(status=404)



@api_view(['GET'])
def get_profile(request):
    user = User.objects.get(username=request.user.username)
    if user.user_type == models.CUSTOMER:
        try:
            profile = user.customer_profile
            return JsonResponse(
                {
                    "nickname": profile.nickname,
                    "phone_num": user.phone_num,
                    "address": profile.customer_add,
                }
            )
        except Exception:
            return JsonResponse(
                {
                    "nickname": "",
                    "phone_num": "",
                    "address": "",
                }
            )
    elif user.user_type == models.SHOP:
        try:
            profile = user.shop_profile
            return JsonResponse(
                {
                    "nickname": profile.shop_name,
                    "phone_num": user.phone_num,
                    "address": profile.shop_add,
                    "info": profile.info,
                }
            )
        except Exception:
            return JsonResponse(
                {
                    "nickname": "",
                    "phone_num": "",
                    "address": "",
                    "info": "",
                }
            )
    else:
        try:
            profile = user.rider_profile
            return JsonResponse(
                {
                    "nickname": profile.rider_name,
                    "phone_num": user.phone_num,
                }
            )
        except Exception:
            return JsonResponse(
                {
                    "nickname": "",
                    "phone_num": "",
                }
            )
